<template>
  <div class="order-detail">
    <el-page-header @back="goBack" content="订单详情" class="page-header" />
    
    <h1 class="page-title">订单详情</h1>
    
    <div class="detail-container" v-loading="loading">
      <el-card v-if="orderDetail" class="order-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单ID">{{ orderDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="工单标题">{{ orderDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ orderDetail.name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderDetail.phone }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{ orderDetail.address }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ orderDetail.des }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPayStatusType(orderDetail.payStatus)">
              {{ getPayStatusText(orderDetail.payStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusType(orderDetail.status)">
              {{ getStatusText(orderDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工单类型">
            <el-tag :type="getTypeType(orderDetail.type)">
              {{ getTypeText(orderDetail.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="关联商品">{{ productName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="调度员">{{ dispatcherName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="接单员工">{{ employeeName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(orderDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(orderDetail.updateTime) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getWorkOrderDetailAPI } from '@/apis/order'
import { getProductByIdAPI } from '@/apis/supplier'
import { getUserListAPI } from '@/apis/sys'

export default {
  name: 'OrderDetail',
  data() {
    return {
      loading: true,
      orderDetail: null,
      productName: '',
      dispatcherName: '',
      employeeName: '',
      userList: []
    }
  },
  created() {
    this.fetchOrderDetail()
  },
  methods: {
    async fetchOrderDetail() {
      this.loading = true
      try {
        // 从路由参数获取订单ID
        const orderId = this.$route.query.id || this.$route.params.id
        
        if (!orderId) {
          this.$message({
            type: 'error',
            message: '缺少订单ID参数'
          })
          this.goBack()
          return
        }
        
        // 调用新的API获取订单详情
        const res = await getWorkOrderDetailAPI(orderId)
        if (res.code === 0) {
          this.orderDetail = {
            id: res.data.id,
            title: res.data.title || '无标题',
            des: res.data.des || '无描述',
            name: res.data.name || '无联系人',
            phone: res.data.phone || '无联系电话',
            address: res.data.address || '无地址',
            payStatus: res.data.payStatus,
            status: res.data.status,
            pic: res.data.pic || '',
            productId: res.data.productId || '',
            dispatcherId: res.data.dispatcherId || '',
            employeeId: res.data.employeeId || '',
            type: res.data.type,
            createTime: res.data.createTime || new Date().toISOString(),
            updateTime: res.data.updateTime || new Date().toISOString()
          }

          // 如果有商品ID，则获取商品名称
          if (this.orderDetail.productId) {
            await this.fetchProductName(this.orderDetail.productId)
          }
          
          // 获取所有用户列表
          await this.fetchUserList()
          
          // 根据ID查找调度员和接单员姓名
          if (this.orderDetail.dispatcherId) {
            this.getDispatcherName(this.orderDetail.dispatcherId)
          }
          
          if (this.orderDetail.employeeId) {
            this.getEmployeeName(this.orderDetail.employeeId)
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取订单详情失败'
          })
          this.goBack()
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取订单详情失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取订单详情失败:', error)
        this.goBack()
      } finally {
        this.loading = false
      }
    },
    
    async fetchProductName(productId) {
      try {
        const res = await getProductByIdAPI(productId)
        if (res.code === 0 && res.data) {
          this.productName = res.data.productName || '未知商品'
        } else {
          this.productName = '商品不存在'
        }
      } catch (error) {
        console.error('获取商品信息失败:', error)
        this.productName = '获取失败'
      }
    },
    
    async fetchUserList() {
      try {
        const res = await getUserListAPI()
        if (res.code === 0 && res.data) {
          this.userList = res.data
        } else {
          console.error('获取用户列表失败:', res.msg || '未知错误')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },
    
    getDispatcherName(dispatcherId) {
      const user = this.userList.find(u => u.id == dispatcherId || u.userId == dispatcherId)
      this.dispatcherName = user ? (user.userName || user.name || '未知用户') : '用户不存在'
    },
    
    getEmployeeName(employeeId) {
      const user = this.userList.find(u => u.id == employeeId || u.userId == employeeId)
      this.employeeName = user ? (user.userName || user.name || '未知用户') : '用户不存在'
    },

    goBack() {
      this.$router.go(-1)
    },
    
    getStatusType(status) {
      switch (status) {
        case 0:
          return '' // 待分配
        case 1:
          return 'warning' // 处理中
        case 2:
          return 'success' // 已完成
        case 3:
          return 'danger' // 已取消
        case 4:
          return 'primary' // 已评价
        default:
          return 'info'
      }
    },
    
    getStatusText(status) {
      switch (status) {
        case 0:
          return '待分配'
        case 1:
          return '处理中'
        case 2:
          return '已完成'
        case 3:
          return '已取消'
        case 4:
          return '已评价'
        default:
          return '未知状态'
      }
    },
    
    getPayStatusType(payStatus) {
      switch (payStatus) {
        case 1:
          return 'success'
        default:
          return 'info'
      }
    },
    
    getPayStatusText(payStatus) {
      switch (payStatus) {
        case 1:
          return '已支付'
        default:
          return '未支付'
      }
    },
    
    getTypeType(type) {
      switch (type) {
        case 0:
          return '' // 普通
        case 1:
          return 'danger' // 紧急
        case 2:
          return 'primary' // 维修
        case 3:
          return 'warning' // 保养
        default:
          return 'info'
      }
    },
    
    getTypeText(type) {
      switch (type) {
        case 0:
          return '普通'
        case 1:
          return '紧急'
        case 2:
          return '维修'
        case 3:
          return '保养'
        default:
          return '未知类型'
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.order-detail {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
  text-align: center;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.detail-container {
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  text-align: left;
}

.order-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
}
</style>